use std::fs::File;
use std::io::{BufReader, BufRead};



pub fn converter(input: &str, tp: &str) -> String {
    let phrase_file = if tp == "s2t" {
        "STPhrases.txt"
    } else {
        "TSPhrases.txt"
    };

    let char_file = if tp == "s2t" {
        "STCharacters.txt"
    } else {
        "TSCharacters.txt"
    };

    // 尝试整个短语转换
    let file = File::open(phrase_file).unwrap();
    let reader = BufReader::new(file);

    // 逐行读取文件
    for line in reader.lines() {
        // 处理每一行
        let line = line.unwrap();  // 处理 Result<String, io::Error>
        let pair = line.split("\t").collect::<Vec<&str>>();
        if input == pair[0] {
            return pair[1].to_string();
        }
    }

    // 没有找到匹配的短语, 逐字转换

    let mut result = Vec::new();
    for ch in input.chars() {
        let file = File::open(char_file).unwrap();
        let reader = BufReader::new(file);   

        let mut found = false;
        for line in reader.lines() {
            let line = line.unwrap();
            let pair = line.split("\t").collect::<Vec<&str>>();
            if ch.to_string() == pair[0] {
                result.push(pair[1].split(" ").collect::<Vec<&str>>()[0].to_string());
                found = true;
                break;
            }
        }
        if !found {
            result.push(ch.to_string());
        }
    }
    result.join("")
}
